<?php

class SocialOrigin_2 extends IOSocial {

	protected $app_id			= 2262375;
	//protected $api_key			= "6IZKMwvfSG";
	protected $api_secret_key	= "ulE1iDjNtxPAThxzU0N8";
	protected $api_link			= "http://api.vkontakte.ru/api.php";
	protected $version			= "2.0";
	protected $viewer_id;

	public function __construct($api = Array()) {
		$this->viewer_id = $api["viewer_id"];
		if ($this->viewer_id = null) {
			$this->secure = 1;
		}
		$this->settings = $api;
		$this->hostData = $this->extractHostData($this->api_link);
	}

	public function checkAuthorization() {
		if ($this->settings["auth_key"] = md5($this->app_id . '_' . $this->settings["viewer_id"] . '_' . $this->api_secret_key)) {
			return true;
		} else {
			return false;
		}
	}

	/* Методы апи */
	public function getProfile($uids = Array()) {
		$this->secure = 1;
		$this->request["uids"] = implode(",", $uids);
		$this->request["fields"] = "uid,first_name,last_name,nickname,sex,bdate,photo,photo_medium,photo_big,online";

		$this->method = "getProfiles";
		$req = $this->getApiRequest($this->expire_time);
		$result = array();
		if (is_object($req) or is_array($req)) {
			foreach ($req as $value) {
				$result[$value["uid"]] = $value;
			}
		}
		return $result;
	}

	/**
	 * Возвращает список друзей пользователя
	 * @param mixed $uid
	 */
	public function getFriends($uid) {
		$this->secure = 1;
		$this->request["uid"] = $uid;
		$this->request["fields"] = "uid,first_name,last_name,nickname,sex,bdate,photo,photo_medium,photo_big,online";
		$this->method = "friends.get";
		$req = $this->getApiRequest($this->expire_time);
		$result = array();
		if (is_object($req) or is_array($req)) {
			foreach ($req as $value) {
				$result[$value["uid"]] = $value;
			}
		}
		return $result;
	}

	/**
	 * Устанавливает статус приложения
	 * @param mixed $uid
	 * @param mixed $status
	 */
	public function saveAppStatus($uid, $status) {
		$this->secure = 1;
		$this->request["uid"] = $uid;
		$this->request["status"] = $status;
		$this->method = "secure.saveAppStatus";
		return $this->getApiRequest($this->expire_time);
	}

	public function setCounter($uid, $counter) {
		$this->secure = 1;
		$this->request["uid"] = $uid;
		$this->request["counter"] = $counter;
		$this->method = "secure.setCounter";
		return $this->getApiRequest(0);
	}

	/**
	 * Списывает голоса со счета пользователя на счет приложения (в сотых долях).
	 * @param mixed $uid - ID ПЕРСОНАЖА
	 * @param mexed $votes - количество списываемых с пользователя голосов (в сотых долях).
	 */
	public function withdrawVotes($uid, $votes) {
		$this->secure = 1;
		$this->request['uid'] = $uid;
		$this->request['votes'] = $votes;
		$this->method = "secure.withdrawVotes";
		return $this->getApiRequest(0);
	}

	/**
	 * Возвращает баланс пользователя на счету приложения в сотых долях голоса. .
	 * @param mixed $uid - ID ПЕРСОНАЖА
	 */
	public function getBalance($uid) {
		$this->secure = 1;
		$this->request['uid'] = $uid;
		$this->method = "secure.getBalance";
		return $this->getApiRequest(0);
	}

	/**
	 * Поднимает рейтинг юзера в контакте
	 * @param mixed $uid
	 * @param mixed $rat
	 * @param mixed $message
	 */
	public function addRating($uid, $rate, $message = null) {
		$this->secure = 1;
		$this->request['uid'] = $uid;
		$this->request['rate'] = $rate;
		if ($message != null) {
			$this->request['message'] = $message;
		}
		$this->method = "secure.addRating";
		return $this->getApiRequest(0);
	}

	//secure.sendNotification
	/**
	 * Отправляет уведомление пользователю.
	 */
	public function Notification($uids = Array(), $message) {
		$this->secure = 1;
		$this->request['uids'] = implode(",", $uids);
		$this->request['message'] = $message;
		$this->method = "secure.sendNotification";
		return $this->getApiRequest(0);
	}

	/* Метод оправки Запросов clsHtmlSource.php */

	protected function genSignature($request_params = Array()) {
		$signature = "";
		foreach ($request_params as $key => $value) {
			$signature .= $key . "=" . $request_params[$key];
		}
		if ($this->secure == 1) {
			$signature = $signature . $this->api_secret_key;
		} else {
			$signature = $this->viewer_id . $signature . $this->api_key;
		}
		return md5($signature);
	}

	protected function getApiRequest($expir = 600) {
		# Настройки соединения.
		$request_params = Array();
		if (count($this->request) > 0) {
			foreach ($this->request as $key => $value) {
				$request_params[$key] = $value;
			}
		}

		$request_params['api_id'] = $this->app_id;
		$request_params['format'] = $this->api_format;
		$request_params['method'] = $this->method;
		$request_params['v'] = $this->version;
		if ($this->secure == 1) {
			$request_params['random'] = rand(100000, 1000000);
			$request_params['timestamp'] = time();
		}
		ksort($request_params);
		$request_params["sig"] = $this->genSignature($request_params);
		$mcKey = $this->generateMCKey($request_params);
		# Пытаемся получить с запроса
		$result = DB::getMCH()->get($mcKey);
		//if ($result === false or $expir == 0) {

			$comon = new HtmlSource();
			$comon->host = $this->hostData['host'];
			$comon->page = $this->hostData['page'];
			$comon->referer = "http://vkontakte.ru/";
			$comon->strip_responseheader = true;
			# Формируем тело запроса
			foreach ($request_params as $key => $value) {
				$comon->addPostVar($key, $value);
			}
			$result = $comon->getSource();
			if ($expir > 0) {
				db::getMCH()->set($mcKey, $result, 0, $expir);
			}
			unset($comon->postvars);
		//}
		var_dump($result);
		$result = json_decode($result);
		$this->request = Array();
		$this->method = null;
		//var_dump($result);
		return $this->_objectToArray($result->response);
	}

}

?>
